/**
 * @typedef {number[][]} Mat
 * @typedef {[x: number, y: number]} Coord
 * @typedef {[Coord, group: number[]]} M
 */

/**
 * @type {Mat}
 */
const mat = [
  [1, 1, 0, 0, 0],
  [1, 0, 1, 0, 0],
  [1, 0, 0, 0, 0],
  [1, 1, 0, 1, 1],
];
// 单个合并
// 一个合并两个

/**
 * @desc 将矩阵转化为邻接表
 * @param {Mat} mat
 * @returns {Coord[]}
 */
function toAdjacencyList(mat) {
  /**
   * @type {Coord[]}
   */
  const aList = [];
  for (let i = 0; i < mat.length; i++) {
    for (let j = 0; j < mat[i].length; j++) {
      if (mat[i][j] === 1) {
        aList.push([i, j]);
      }
    }
  }
  return aList;
}
const adList = toAdjacencyList(mat);

/**
 * @param {Coord[]} adList
 * @returns {number}
 */
function toGroup(adList) {
  let group = 0;
  for (let i = 0; i < adList.length; i++) {
    const [x, y] = adList[i];
    if (mat[x][y] === 1) {
      mat[x][y] = group;
      group++;
    }
  }
  return group;
}
